/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package linkeddata.arida.ufc.br.endpoints;

import com.hp.hpl.jena.query.QueryExecutionFactory;
import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.query.ResultSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 *
 * @author jeovane
 */
public class GetPredicates extends Prefix {

    private Prefix prefix;

    public GetPredicates(LoadFileUrl load) {
        super(load);
        this.prefix = new Prefix(load);
    }

    private Set<String> getPredicates(String source) {
        Set<String> result = new HashSet<String>();

        if (this.prefix.mapSources().containsKey(source.toLowerCase())) {
            String query = this.prefix.prefixes() + " SELECT DISTINCT ?p WHERE {?s ?p ?o} ";
            ResultSet rs = QueryExecutionFactory.sparqlService(this.prefix.mapSources().get(source).toString(), query).execSelect();

            while (rs.hasNext()) {
                QuerySolution qs = rs.next();
                result.add(qs.get("p").toString());
            }
        }

        return result;
    }

    public Map<String, String> mapPredicates(String source) {
        Map<String, String> mapPredicates = new HashMap<String, String>();

        for (String predicates : getPredicates(source)) {
            String[] property = predicates.split("/");
            if (property[property.length - 1].contains("#")) {
                String[] propertySplit = property[property.length - 1].split("#");
                mapPredicates.put(propertySplit[propertySplit.length - 1], predicates);
            } else {
                mapPredicates.put(property[property.length - 1], predicates);
            }
        }

        return mapPredicates;
    }
    
//    public static void main(String[] args) {
//        String prefix = "https://dl.dropbox.com/u/19076387/prefixes.txt";
//        LoadFileUrl load = new LoadFileUrl(prefix);
//        GetPredicates gp = new GetPredicates(load);
//        String source = "sider";
//
//        for (Iterator it = gp.mapPredicates(source).entrySet().iterator(); it.hasNext();) {
//            Map.Entry entry = (Map.Entry) it.next();
//            //System.out.println(entry.getKey() + ": " + entry.getValue());
//        }
//        
//        for (Iterator it = gp.mapSources().entrySet().iterator(); it.hasNext();) {
//            Map.Entry entry = (Map.Entry) it.next();
//            System.out.println(entry.getKey() + ": " + entry.getValue());
//        }
//        
//        //System.out.println(gp.prefixes());
//    }
}
